<?php

namespace App\Admin\Controllers;

use App\Models\ActivityClassArticle;
use App\Models\ActivityTeamModel;
use App\Models\ActivityTeamUser;
use App\Models\ArticleModel;
use App\Models\AudioStudyArticle;
use App\Models\AudioStudy;
use App\Models\CompanyReadBook;
use App\Models\CompanyReadModel;
use App\Models\WorkModel;
use App\Services\Api\WorkService;
use Encore\Admin\Controllers\AdminController;
use Illuminate\Http\Request;
use App\Models\BookModel;
use App\Models\PersonalRead;
use App\Models\CompanyModel;
use App\Models\ActivityClassModel;
use App\Models\ActivityClassBook;
use App\Models\PersonalReadBook;
use Illuminate\Support\Facades\Cache;

class AdminApiController extends AdminController
{
    //后期 建议封装到services层
    public function redis_team_book_article($key_id,$type,$team_id){
        //统计 文章数量
        if($type == 1){
            $book = CompanyReadBook::where('comapny_read_id',$key_id)
                ->with([
                    'article'=>function($q)use($type,$key_id){
                        $q->select([
                            'id',
                            'book_id',
                            'article_title',
                            //\DB::raw("count(id)"),
                        ])
                            ->with([
                                'class_work'=>function($q)use($type,$key_id){
                                    $q->where('class_type',$type)
                                        ->where('key_id',$key_id)
                                        ->select([
                                            'id',
                                            'key_id',
                                            'book_id',
                                            'type',
                                            'work_id',
                                        ]);
                                }
                            ])
                            ->groupBy('id');
                    },
           /*         'work'=>function($q)use($type){
                        $q->where('class_type',$type)
                        ->select([
                            'id',
                            'key_id',
                            'type',
                            'work_id',
                        ]);
                    }*/
                ])
                ->orderBy('sort','asc')
                ->get()
                ->toArray();
        }elseif ($type == 2){
            $book = ActivityClassBook::where('activity_class_id',$key_id)
                ->with([
                    'article'=>function($q)use($type,$key_id){
                        $q->select([
                            'id',
                            'book_id',
                            'article_title',
                           // \DB::raw("count(id) as article_number"),
                        ])
                            ->with([
                                'class_work'=>function($q)use($type,$key_id){
                                    $q->where('class_type',$type)
                                        ->where('key_id',$key_id)
                                        ->select([
                                            'id',
                                            'key_id',
                                            'book_id',
                                            'type',
                                            'work_id',
                                        ]);
                                }
                            ])
                            ->groupBy('id');
                    },
               /*     'work'=>function($q)use($type){
                        $q->where('class_type',$type)
                            ->select([
                                'id',
                                'key_id',
                                'type',
                                'work_id',
                            ]);
                    }*/
                ])
                ->orderBy('sort','asc')
                ->get()
                ->toArray();
        }elseif ($type == 3){
            $book = PersonalReadBook::where('personal_read_id',$key_id)
                ->with([
                    'article'=>function($q)use($type,$key_id){
                        $q->select([
                            'id',
                            'book_id',
                            'article_title',
                            //\DB::raw("count(id)"),
                        ])
                            ->with([
                                'class_work'=>function($q)use($type,$key_id){
                                    $q->where('class_type',$type)
                                        ->where('key_id',$key_id)
                                        ->select([
                                            'id',
                                            'key_id',
                                            'book_id',
                                            'type',
                                            'work_id',
                                        ]);
                                }
                            ])
                            ->groupBy('id');
                    },
          /*          'work'=>function($q)use($type){
                        $q->where('class_type',$type)
                            ->select([
                                'id',
                                'key_id',
                                'type',
                                'work_id',
                                'book_id',
                            ]);
                    }*/
                ])
                ->orderBy('sort','asc')
                ->get()
                ->toArray();
        }
        //dd($team_id);
        $teamObj = ActivityTeamModel::where('id',$team_id)
            ->first();
        //dd($book);
        if(empty($book)){
            return [];
        }
        //dd($book);
        $article_number = 0;
        $article = [];
        foreach ($book as $k=>$v){
            $article_number += count($v['article']);
            foreach ($v['article'] as $kk=>$vv){
                $article[] = [
                  'book_id'=>$vv['book_id'],
                  'article_id'=>$vv['id'],
                  'article_title'=>$vv['article_title'],
                  'work'=>$vv['class_work'],
                ];
            }
        }
        //dd($article);
        $teamObj->start_time = date("Y-m-d",strtotime($teamObj->start_time));
        $article_number = $article_number - 1;
        //計算结束时间 = 开始时间 + 天数(章节数) + 休息天数
        $end_date =  date('Y-m-d', strtotime("$teamObj->start_time +$article_number day"));
        $all_time = getDatesBetweenTwoDays($teamObj->start_time,$end_date);
        $holiday = [];
        //獲取休息時間
        if(!empty($teamObj->wee_holiday)){
            //休息規則1 按星期几休息
            $holiday = getWeekDays($teamObj->start_time,$teamObj->wee_holiday,$article_number,$end_date);
            //dd($holiday,$teamObj->start_time,$end_date,$article_number,$teamObj->wee_holiday);
            //休息天不進行活动 所以结束时间后移
            $holiday_number = count($holiday);
            //更新结束时间
            $end_date =  date('Y-m-d', strtotime("$end_date +$holiday_number day"));
            $all_time = getDatesBetweenTwoDays($teamObj->start_time,$end_date);
            $holiday = array_column($holiday,'data');

        }

        if(strtotime($teamObj->day_holiday_start) > 0 && strtotime($teamObj->day_holiday_end) > 0){
            $teamObj->day_holiday_start = date("Y-m-d",strtotime($teamObj->day_holiday_start));
            $teamObj->day_holiday_end = date("Y-m-d",strtotime($teamObj->day_holiday_end));
            //休息规则2 按固定时间休息
            $holiday2= getDatesBetweenTwoDays($teamObj->day_holiday_start,$teamObj->day_holiday_end);
            //dd($holiday2);
            //求差集 不同的休息日期

            $intersection = array_diff($holiday2,$holiday);

            $intersection_number = count($intersection);

            if($intersection_number >0){
                //更新结束时间
                $end_date =  date('Y-m-d', strtotime("$end_date +$intersection_number day"));
                $all_time = getDatesBetweenTwoDays($teamObj->start_time,$end_date);
                //合并去重 重置key
                $holiday = array_keys(array_flip($holiday2) + array_flip($holiday));
                //dd($holiday);
            }
        }

        //檢查最後新加入的時間有沒有符合 規則1
        if(!empty($teamObj->wee_holiday)){
            //休息規則1 按星期几休息
            $holiday3 = getWeekDays($teamObj->start_time,$teamObj->wee_holiday,$article_number,$end_date);
            $holiday3 = array_column($holiday3,'data');
            //dd($holiday,$holiday3);
            $holiday_intersection = array_diff($holiday3,$holiday);
            //dd($holiday_intersection);
            //休息天不進行活动 所以结束时间后移
            $holiday_intersection_number = count($holiday_intersection);
            //更新结束时间
            $end_date =  date('Y-m-d', strtotime("$end_date +$holiday_intersection_number day"));
            $all_time = getDatesBetweenTwoDays($teamObj->start_time,$end_date);
            //合并去重 重置key
            $holiday = array_keys(array_flip($holiday) + array_flip($holiday3));
        }

        //遍历对应的书本 文章
        $data = [];
        $work_intersection = array_diff($all_time,$holiday);
        //dd($work_intersection,$article);
        $work_intersection = array_values($work_intersection);
        //需要上课
        foreach ($work_intersection as $kkk=>$vvv){
            if(!empty($article[$kkk])){
                if(!empty($article[$kkk]['work'])){
                    foreach ($article[$kkk]['work'] as $k1=>$v1){
                        $article[$kkk]['work'][$k1]['article_id'] = $article[$kkk]['article_id'];
                        $article[$kkk]['work'][$k1]['data'] = $vvv;
                    }
                }
                $data[$vvv] = [
                  'article_id'=>$article[$kkk]['article_id'],
                  'book_id'=>$article[$kkk]['book_id'],
                  'article_title'=>$article[$kkk]['article_title'],
                  'work'=>$article[$kkk]['work'],
                ];
            }else{
                $data[$vvv] = [];
            }
        }

        if(count($holiday) > 0){
            $holiday_array = [];
            foreach ($holiday as $kk=>$vv){
                $holiday_array[$vv] = [];
            }
            $data = $data + $holiday_array;
        }
        //存进redis
        //$redis_key = 'team_work_'.$team_id;
        //dd($holiday);
        $redis_key = env('REDIS_KEY_TEAM_WORK').$team_id;
        $data = json_encode($data);
        $res = Cache::put($redis_key,$data);

        //存储数据库
        $teamObj->read_info = $data;
        $res2 = $teamObj->save();
        if($res && $res2){
            return true;
        }else{
            return false;
        }
    }

    public function get_team_statistics($team_id,$start_time,$end_time){
        $teamObj = ActivityTeamModel::where('id',$team_id)->first();
        //获取缓存
        $redis_key = env('REDIS_KEY_TEAM_WORK').$team_id;
        $work_data = Cache::get($redis_key);
        if(!empty($work_data)){
            $work_data = json_decode($work_data,true);
        }else{
            $api = new AdminApiController();
            $res = $api->redis_team_book_article($teamObj->key_id,$teamObj->class_type,$teamObj->id);
            //dd($res);
            $work_data = Cache::get($redis_key);
            $work_data = json_decode($work_data,true);
        }
        //$data = [];
        //dd($work_data);
        $number = 0;
        foreach ($work_data as $k=>$v){
            if($k >= $start_time && $k<= $end_time){
                if(!empty($v['work'])){
                    $number += count($v['work']);
                }
            }
        }
        //dd($data);
        return $number;
    }

    public function get_team_user_study(){

    }

    public function getBook(Request $requests,BookModel $bookModel){
        $q = $requests->get('q');
        return $bookModel->where('book_title','like', "%$q%")->paginate(10, ['id', 'book_title as text']);
    }

   public function activity_book(Request $requests,ActivityClassBook $activityClassBook){
       $q = $requests->get('q');
       $book_id = $activityClassBook->where('activity_class_id',$q)->pluck('book_id');
        return BookModel::whereIn('id',$book_id)->get(['id','book_title as text']);
   }

    public function audio_article(Request $requests,ArticleModel $articleModel,AudioStudyArticle $studyArticle){
        $q = $requests->get('q');
        $article_ids = $studyArticle->where('audio_study_id',$q)->pluck('article_id');
        //->get(['id', DB::raw('name as text')])
        return $articleModel->whereIn('id',$article_ids)->get(['id','title as text']);
    }

    public function personal_article(Request $requests,ArticleModel $articleModel,PersonalRead $personalRead){
        $q = $requests->get('q');
        $book_ids = $personalRead->where('id',$q)->pluck('book_id')->toArray();
        //dd($q,$article_ids);
        //->get(['id', DB::raw('name as text')])
        return $articleModel->whereIn('book_id',$book_ids)->get(['id','article_title as text']);
    }


    public function book_article(Request $requests,ArticleModel $articleModel,ActivityClassArticle $activityClassArticle){
        $q = $requests->get('q');
        //$article_ids = $activityClassArticle->where('class_id',$q)->pluck('article_id');
        //->get(['id', DB::raw('name as text')])
        return $articleModel->where('book_id',$q)/*->whereIn('type',[1,3])*/->get(['id','article_title as text']);
    }

    public function company_article(Request $requests,ArticleModel $articleModel,ActivityClassArticle $activityClassArticle){
        $q = $requests->get('q');
        $article_ids = $activityClassArticle->where('class_id',$q)->pluck('article_id');
        //->get(['id', DB::raw('name as text')])
        return $articleModel->whereIn('id',$article_ids)->get(['id','article_title as text']);
    }

    public function get_work(Request $request,WorkModel $workModel){
        $q = $request->input('q');
        return $workModel->where('type',$q)->get(['id','title as text']);
    }

    public function company_read(Request $request,CompanyReadModel $companyReadModel){

    }

    public function company_list(Request $request,CompanyModel $companyModel){
        return $companyModel->where('status',3)->get(['id','company_name as text']);
    }

    public function company_activity_class(Request $request,ActivityClassModel $activityClassModel){
        return $activityClassModel/*->where('company_id',$request->input('q'))*/->get(['id','class_name as text']);
    }

    public function company_read_list(Request $request,CompanyReadModel $companyReadModel){
        return $companyReadModel->where('company_id',$request->input('q'))->get(['id','title as text']);
    }

    public function personal_book(Request $request,PersonalRead $personalRead,BookModel $bookModel,PersonalReadBook $personalReadBook){
        $q = $request->input('q');
        $book_id = $personalReadBook->where('personal_read_id',$q)->pluck('book_id');
        return BookModel::whereIn('id',$book_id)->get(['id','book_title as text']);
    }

    public function company_read_book_article(Request $request,CompanyReadModel $companyReadModel,BookModel $bookModel,ArticleModel $articleModel){
        $q = $request->input('q');
        $book_id = $companyReadModel->where('id',$q)->value('book_id');
        return $articleModel->where('book_id',$book_id)->get(['id','article_title as text']);
    }

    public function audio_list(Request $request,ArticleModel $articleModel,AudioStudyArticle $studyArticle,AudioStudy $audioStudy){
        $q = $request->input('q');
        return $audioStudy->where('company_id',$q)->get(['id','article_title as text']);
    }

    //一鍵審核 单个小组
    public function release(Request $request,ActivityTeamUser $teamUser)
    {
        $ids = $request->get('ids');
        if(!empty($ids)){
            $teamUser->whereIn('id',$ids)->update([
                'team_user_stash'=>1
            ]);
        }
    }

    //多个小组 一键审核
    public function all_team_examine(Request $request,ActivityTeamUser $teamUser){
        $ids = $request->get('ids');
        if(!empty($ids)){
            $teamUser->whereIn('team_id',$ids)->update([
                'team_user_stash'=>1
            ]);
        }
    }
}
